package net.csdra.libraryborrowing.service.user;

import net.csdra.libraryborrowing.domain.user.TransferBorrowInfo;
import net.csdra.libraryborrowing.domain.user.TransferBorrowInfoRepository;
import net.csdra.libraryborrowing.domain.user.User;
import net.csdra.libraryborrowing.domain.user.UserBorrow;
import net.csdra.libraryborrowing.util.Utils;
import org.apache.tomcat.util.modeler.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import java.nio.file.AccessDeniedException;

/**
 * Created by add on 2017/10/17.
 */
public class TransferBorrowInfoServiceImpl implements TransferBorrowInfoService {

    CurrentUserInfo currentUserInfo;
    UserBorrowComponent userBorrowComponent;
    UserComponents userComponents;
    TransferBorrowInfoRepository transferBorrowInfoRepository;

    @Autowired
    public TransferBorrowInfoServiceImpl(CurrentUserInfo currentUserInfo, UserBorrowComponent userBorrowComponent, UserComponents userComponents,
                                         TransferBorrowInfoRepository transferBorrowInfoRepository)
    {
        this.currentUserInfo = currentUserInfo;
        this.userBorrowComponent = userBorrowComponent;
        this.userComponents = userComponents;
        this.transferBorrowInfoRepository = transferBorrowInfoRepository;
    }

    @Override
    public TransferBorrowInfo generateTransferBorrowInfo(GenerateTransferBorrowInfo generateTransferBorrowInfo)
            throws AccessDeniedException {
        Assert.notNull(generateTransferBorrowInfo,"参数不能为空");
        Assert.hasLength(generateTransferBorrowInfo.getBookCopyId(), "id不能为空");
        User currentUser = this.currentUserInfo.get();
        UserBorrow userBorrow = this.userBorrowComponent.getUserBorrowByBookCopyId(
                currentUser.getId(), generateTransferBorrowInfo.getBookCopyId()
        );
        Assert.notNull(userBorrow, "没有借阅信息");
        TransferBorrowInfo transferBorrowInfo = Utils.createAutoSet(TransferBorrowInfo.class, currentUser.getUserName());
        //TODO 待确认
        transferBorrowInfo.setMetaId("");
        transferBorrowInfo.setOriginUserId(currentUser.getId());
        transferBorrowInfo.setTargetUserId(
                this.userComponents.getUserId(generateTransferBorrowInfo.getRecipientUserName())
        );
        TransferBorrowInfo result = this.transferBorrowInfoRepository.save(transferBorrowInfo);
        Utils.copy(transferBorrowInfo, result);
        return result;
    }
}
